package com.edianping.store.db;

import java.sql.*;

public class DBInfo {

	private static String dburl;

	private static String mySqlDriver = "org.gjt.mm.mysql.Driver";

	private static String username;

	private static String passwd;

	static {
		initDB();
	}

	/**
	 * do some db initial work here read urls, dbuser, passwd
	 * 
	 */
	private static void initDB() {
		com.edianping.config.DBInfoBean dbBean = com.edianping.util.XmlUtil
				.parseDBInfo("dbinfo.xml");

		mySqlDriver = "org.gjt.mm.mysql.Driver";
		dburl = dbBean.dburl;// "jdbc:mysql://192.168.1.4/nsws?autoReconnect=true&useUnicode=true&characterEncoding=utf8";
		username = dbBean.username;// ."root";
		passwd = dbBean.passwd;// "alazhu@2908";
		try {
			Class.forName(mySqlDriver);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 这个方法是给连接池用的，其他package是看不到的。。
	 * 
	 * @return
	 */
	static Connection getConnection() throws SQLException {
		Connection conn = null;
		conn = DriverManager.getConnection(dburl, username, passwd);
		return conn;
	}

	// charset test. ok
	// utf -8

	private static void viewDb() {
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = getConnection();
			stmt = conn.createStatement();
			String sql = "select title, author from page_id";
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				String title = rs.getString("title");
				String author = rs.getString("author");
				System.out.print(title + "::" + author + "\n");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

//	private static void insert() {
//		Connection conn = null;
//		Statement stmt = null;
//		try {
//			conn = DriverManager.getConnection(dburl, username, passwd);
//			stmt = conn.createStatement();
//			String title = "南京夫子庙2";
//			String author = "jacky";
//			String sql = "insert into page_id (title,author) values ('" + title
//					+ "','" + author + "') ";
//			stmt.executeUpdate(sql);
//		} catch (SQLException e) {
//			e.printStackTrace();
//		}
//	}

	public static void main(String args[]) {
		initDB();
		viewDb();

	}
}
